﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Borton.Beans;
using Borton.Data;
using System.Windows.Forms;
namespace Borton
{
    class Identifier : Field
    {
        public Bean bean = null;
        private Type beanType;
        public KeyValue[] data;

        public Identifier(String columnName, Type beanType) : base(columnName, FieldType.IDENTIFIER)
        {
            this.beanType = beanType;
        }

        public Identifier(String columnName, Bean bean)
            : base(columnName, FieldType.IDENTIFIER)
        {
            this.bean = bean;
        }

        public void initBean()
        {
            if (bean == null)
            {
                bean = (Bean)Activator.CreateInstance(beanType);
            }
        }

        public override String getValueForDisplay()
        {
            initBean();
            return this.bean.getDisplayName();
        }
        public override String getValueForSave()
        {
            initBean();
            return this.bean.getId().getValueForSave();
        }

        public Bean getBean()
        {
            initBean();
            return bean;
        }

        public override void setValue(String value)
        {
            initBean();
            try
            {
                this.bean.getId().setValue(Int32.Parse(value).ToString());
                bean.load();
            } catch (FormatException) {
            }
        }

        private void initControl()
        {
            initBean();
            Bean[] beans = bean.getAll();
            KeyValue[] data = new KeyValue[beans.Length];
            for (int i = 0; i < beans.Length; i++)
            {
                data[i] = new KeyValue(beans[i].getId().getValueForSave(), beans[i].getDisplayName());
            }
            ComboBox combo = new ComboBox();
            combo.FormattingEnabled = true;
            combo.DataSource = data;
            combo.ValueMember = "key";
            combo.DisplayMember = "value";
            combo.Name = this.columnName + "Combo";
            combo.Size = new System.Drawing.Size(100, 20);
            combo.DropDownStyle = ComboBoxStyle.DropDownList;
            if (this.getValueForSave() != null)
            {
                combo.SelectedValue = this.getValueForSave();
            }
            this.control = combo;
        }

        public override Control getControl(bool readOnly)
        {
            if (control == null) {
                initControl();
            }
            return base.getControl(readOnly);
        }

        public override void saveState()
        {
            initBean();
            bean.getId().setValue(((ComboBox)control).SelectedValue.ToString());
            bean.load();
        }
    }
}
